from datetime import datetime
import os

from django.db import models
from django.db.models.signals import post_save
from api.utils.db_functions import make_uuid, make_short_uuid
from api.utils.enums import MediaType, FilePurpose
from api.utils.models import AbstractBase
from django.utils.translation import gettext_lazy as _


class Porduct(AbstractBase):
    product_id = models.IntegerField(help_text="商品ID", default=0)
    title = models.CharField(help_text="商品标题", max_length=256)
    businss_id = models.IntegerField(help_text="生产商ID", default=0)
    description = models.CharField(help_text="商品描述", default="", max_length=256)
    is_public = models.BooleanField("是否发布", default=False)

    def images(self):
        return self.files.filter(type=MediaType.IMAGE.value, deleted=False)

    def videos(self):
        return self.files.filter(type=MediaType.VIDEO.value, deleted=False)


def file_path(instance, file):
    file_ext = file.split(".")[-1]
    filename = "%s.%s" % (make_short_uuid(), file_ext)
    now = datetime.now()
    parent_folder = "product/%s/%s/%02d/%02d/" % (instance.type, now.year, now.month, now.day)

    return os.path.join(parent_folder, filename)


class PorductImage(AbstractBase):
    purpose = models.CharField("文件用途", choices=FilePurpose.to_choices(), default="", max_length=64)
    file = models.FileField(help_text="文件Url", upload_to=file_path, max_length=256)
    product = models.ForeignKey(
        "Porduct", on_delete=models.CASCADE, related_name="files", verbose_name=_("Group")
    )
    type = models.CharField(
        choices=MediaType.to_choices(), default=MediaType.IMAGE.value, max_length=32
    )
